<template>
  <div class="container">
    <div class="form">
      <el-form label-width="100px" :label-position="!this.isPC() ? 'top' : 'left'">
        <el-form-item>
          <template slot="label">
            <span>信访主题<span style="color: red; margin-left: 5px;">*</span></span>
          </template>
          <el-input v-model="form.caseTitle" placeholder="请输入信访主题，限250字以下" :disabled="!canEdit"></el-input>
        </el-form-item>
        <div v-if="dictList.length > 0">
          <el-form-item :label="dictList[0].name">
            <el-select v-model="form.caseType" :placeholder="'请选择'+dictList[0].name" style="width: 100%;" :disabled="!canEdit" clearable>
              <el-option :label="child.name" :value="child.id" v-for="child in dictList[0].child" :key="child.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="信访内容">
          <template slot="label">
            <span style="display: flex;" :style="{'flex-direction': !this.isPC() ? 'row' : 'column'}"><span style="width: 100px;">信访内容<span style="color: red; margin-left: 5px;">*</span></span>
            <span style="color: red">图片小于1M</span>
            </span>
          </template>
          <div class="component-editor" ref="editor" v-if="canEdit"></div>
          <div v-if="!canEdit" v-html="form.caseContent" style="border: 1px solid #d9d9d9; width: 100%; padding: 0 10px; color: #C0C4CC; background-color: #F5F7FA; cursor: not-allowed;"></div>
          <input ref="uploadInput" style="display:none;" type="file" @change="uploadFile($event, form.caseAttachment)" multiple>
          <span class="addfilebtn" @click="$refs.uploadInput.click()" v-if="canEdit"><i class="el-icon-paperclip"></i>添加附件</span>
          <div class="fileitem" v-for="(file, idx) in form.caseAttachment" :key="idx">
            <span style="cursor: pointer;" @click="downloadFile(file.url, file.name)">
              <img style="width:16px;height:16px;position:relative;top:-2px;margin-right:2px;" :src="getPic(file.name)" alt="">{{file.name}}
            </span>
            <span class="uploadtip" v-if="file.url" @click="delFile(idx, form.caseAttachment)"><i class="el-icon-delete" v-if="canEdit"></i></span>
            <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
          </div>
        </el-form-item>
        <el-form-item label="是否匿名">
          <el-radio-group v-model="form.caseIsAnonymity">
            <el-radio label="1" :disabled="!canEdit">匿名</el-radio>
            <el-radio label="0" :disabled="!canEdit">实名{{canEdit ? '（'+userInfo.realName+'）' : ''}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="isdeal || canViewResult">
          <el-form-item label="转达给">
            <div @click="selectDingUsers('caseConveyIdArr','caseConveyName','caseConveyId', 'caseConveyNameArr', 300)" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
            <div v-for="(member, idx) in form.caseConveyNameArr" :key="idx">
              <div class="select-btn" style="padding: 0;" @click="delMember('caseConveyIdArr','caseConveyName','caseConveyId', 'caseConveyNameArr', idx)">{{member}}<div class="del" v-if="isdeal">移除</div></div>
            </div>
          </el-form-item>
          <el-form-item label="处理结果">
            <el-input v-model="form.caseResult" type="textarea" rows="4" :disabled="!isdeal"></el-input>
          </el-form-item>
          <el-form-item label="处理人" v-if="form.caseHandlerName">{{form.caseHandlerName}}</el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-if="canEdit">提交</el-button>
          <el-button type="primary" @click="submitDealForm" v-if="isdeal">提交处理意见</el-button>
          <el-button @click="$router.go(-1)">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import sinaEmotions from '@/assets/emotion/sina'
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'

export default {
  data () {
    return {
      dictList: [],
      form: {
        caseTitle: '',
        caseContent: '',
        caseAttachment: [],
        caseType: '',
        caseIsAnonymity: '0',
        caseConveyId: '',
        caseConveyIdArr: '',
        caseConveyName: '',
        caseConveyNameArr: [],
        caseResult: '',
        caseHandlerName: '',
        caseStatus: '',
      },
      editor: null,
      handleType: 'add', //add、edit、view、deal
    };
  },
  mixins: [dingMixin],
  mounted () {
    this.getDictList();
    this.init();
  },
  computed: {
    canEdit() {
      return this.handleType === 'add' || this.handleType === 'edit'
    },
    canViewResult() {
      return this.form.caseStatus ==='2'
    },
    isdeal() {
      return this.handleType === 'deal'
    }
  },
  methods: {
    async init() {
      this.handleType = this.$route.params.handleType;
      if(this.$route.params.id) {
        let caseInfo = await this.$httpN.postB('petition/case/info', { id: this.$route.params.id })
        caseInfo.caseConveyIdArr = caseInfo.caseConveyId !== '' ? caseInfo.caseConveyId.split(",") : [];
        caseInfo.caseConveyNameArr = caseInfo.caseConveyName !== '' ? caseInfo.caseConveyName.split(",") : [];
        caseInfo.caseAttachment = caseInfo.caseAttachment ? JSON.parse(caseInfo.caseAttachment) : [];
        this.form = caseInfo
      }
      if(this.canEdit) {
        let E = window.wangEditor;
        var editor = new E(this.$refs.editor)
        editor.customConfig.uploadImgServer = this.$http.adornUrl('/fileUpload');
        editor.customConfig.uploadImgHeaders = {'token': this.$cookie.get('token')}
        editor.customConfig.uploadFileName = 'file'
        editor.customConfig.menus = ['head','bold','justify','emoticon','image']
        editor.customConfig.uploadImgHooks = {
          customInsert: function (insertImg, result, editor) {
            var url = result.url + '?x-oss-process=style/forbid'
            insertImg(url)
          }
        }
        editor.customConfig.emotions = [{title:'默认',type: 'image',content: sinaEmotions}]
        editor.create();
        this.editor = editor;
        if(this.form.id) editor.txt.html(this.form.caseContent);
      }
    },
    async getDictList() {
      let {list} = await this.$httpN.postB('petition/dict/list', {limit: 999});
      this.dictList = list;
      this.dictList.forEach(item => {
        this.getSubDictList(item)
      })
    },
    async getSubDictList(item) {
      let {list} = await this.$httpN.postB('petition/dict/list', {limit: 999, pid: item.id});
      this.$set(item, 'child', list)
    },
    async uploadFile(e, target) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.$message.error('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
          size: file.size,
          uploader: $this.userInfo.realName,
          time: dateUtil.thisDay()
        }
        target.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            target.pop();
          }
        })
      })
      e.target.value = '';
    },
    delFile(idx, target){
      target.splice(idx, 1)
    },
    downloadFile: function (url, fileName) {//跨域文件路径、下载到本地的文件名
      if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url)) return this.dingPreviewPic(url);
      if(!url) return;
      var x = new XMLHttpRequest();
      x.open("GET", url, true);
      x.responseType = 'blob';
      x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = fileName;
        a.click()
      }
      x.send();
    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    },
    selectDingUsers(ids, name, idsStr, names, num){
      if(!this.isdeal) return
      this.complexPicker(num, [], this.form[ids]).then((data)=>{
        this.form[ids] = data.map(item => item.emplId);
        this.form[names] = data.map(item => item.name);
        this.form[idsStr] = this.form[ids].join(',');
        this.form[name] = this.form[names].join(',');
        this.submitConveyForm()
      })
    },
    delMember(ids, name, idsStr, names, idx) {
      if(!this.isdeal) return
      this.form[ids].splice(idx,1); 
      this.form[names].splice(idx,1); 
      this.form[idsStr] = this.form[ids].join(',')
      this.form[name] = this.form[names].join(',')
      this.submitConveyForm()
    },
    async submitForm() {
      if(!this.form.caseTitle) return this.$message.error('请输入信访主题');
      if(this.form.caseTitle.length > 250) return this.$message.error('信访主题不要超过250个字');
      this.form.caseContent = this.editor.txt.html();
      if(!this.form.caseContent || this.form.caseContent==='<p><br></p>') return this.$message.error('请输入信访内容');
      if(this.form.caseAttachment.filter(item => !item.url).length > 0) return this.$message.error('附件正在上传，请稍候……');
      let apply = {
        caseTitle: this.form.caseTitle,
        caseType: this.form.caseType,
        caseContent: this.form.caseContent,
        caseIsAnonymity: this.form.caseIsAnonymity,
        caseAttachment: this.form.caseAttachment,
      }
      if(!!this.form.id) apply.id = this.form.id
      if(!await this.$httpN.postB(!this.form.id ? 'petition/case/save' : 'petition/case/update', apply)) return
      formUtil.submitSuccess('保存成功');
      window.NEEDREFRESH = true;
      this.$router.replace({ name: !this.isPC() ? 'letter-mobileList' : 'letter-list'})
    },
    async submitConveyForm() {
      if(!await this.$httpN.postB('petition/case/conveyCase', {
        id: this.form.id,
        caseConveyId: this.form.caseConveyId,
        caseConveyName: this.form.caseConveyName,
      })) return
      formUtil.submitSuccess('保存成功');
      window.NEEDREFRESH = true;
    },
    async submitDealForm() {
      if(!this.form.caseResult) return this.$message.error('请输入处理结果');
      if(!await this.$httpN.postB('petition/case/handleCase', {
        id: this.form.id,
        caseResult: this.form.caseResult,
      })) return
      formUtil.submitSuccess('保存成功');
      window.NEEDREFRESH = true;
      this.$router.go(-1);
    },
  }
}
</script>

<style lang='scss' scoped>
.container {
  .form {
    margin: 30px 20px;
    .component-editor {
      width: 100%;
      border: 1px solid #d9d9d9;
      line-height: 1.15;
      .w-e-toolbar{
        flex-wrap:wrap;
      }
      .w-e-text{
        overflow-y: auto;
      }
      img {
        max-width: calc(100% - 20px) !important;
      }
    }
    .addfilebtn{
      line-height: 24px;
      cursor: pointer;
      color: #409EFF;
      display: inline-block;
    }
    .fileitem{
      line-height: 32px;
      margin-top: 5px;
      margin-bottom: 5px;
      background: #F5F5F5;
      width: 100%;
      padding-left:15px;
      font-size: 12px;
      .uploadtip{
        float:right;
        margin-right: 20px;
        cursor: pointer;
      }
    }
    .select-btn{
      float:left;
      font-weight: normal;
      margin-right: 5px;
      margin-bottom: 10px;
      width: 80px;
      height: 28px;
      border-radius: 30px;
      background: #FAFAFA;
      border: 1px solid #ECECEC;
      position: relative;
      padding-left: 21px;
      line-height: 28px;
      color: #7982A7;
      font-size: 12px;
      text-align: center;
      cursor: pointer;
      span{
        position: absolute;
        top: 1px;
        left: 1px;
        display:block;
        height: 24px;
        width: 24px;
        background: #CACACA;
        color: white;
        border-radius: 50%;
        text-align: center;
        line-height: 24px;
        img{
          width: 24px;
          height: 24px;
          border-radius: 50%;
        }
      }
      .del{
        position: absolute;
        top:0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 30px;
        color: white;
        text-align: center;
        background:rgba(130, 130, 130, 0.9);
        display: none;
      }
      &:hover{
        .del{
          display: block;
        }
      }
    }
  }
}
</style>